/*
 * main.c
 *
 *  Created on: 27/nov/2013
 *      Author: Ialenti Andrea, Marangon Fabio
 */

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define FILE_PATH	"../RO2_TSP_CPLEX/lib/tsp/random/"
#define MIN			0
#define MAX			1000
#define DFLT_NODES	26

int nextRandom(int min, int max) {
	int random = min + rand() / (RAND_MAX / (max - min));
	return random;
}

int main(int argc, char **argv) {
	srand(time(NULL));

	int size = (argc > 1) ? atoi(argv[1]) : DFLT_NODES;
	char *name = (char*) calloc(100, sizeof(char));
	sprintf(name, "rand_%d", size);
	char *fName = (char*) calloc(100, sizeof(char));
	sprintf(fName, "%s%s.tsp", FILE_PATH, name);

	fprintf(stdout, "\nRunning random graph generator, number of nodes: %d. . .\n", size);
	fprintf(stdout, "Graph data will be written to file '%s'. . .\n\n", fName);

	//	Open file writer.
	FILE * file;
	if ((file = fopen (fName, "wt")) == NULL) {
		fprintf(stdout, "***Error opening file writer!\n");
		return -1;
	}

	//	Print file header.
	fprintf(file, "NAME: %s\n", name);
	fprintf(file, "TYPE: RANDOM\n");
	fprintf(file, "DIMENSION: %d\n", size);
	fprintf(file, "EDGE_WEIGHT_TYPE: EUC_2D\n");
	fprintf(file, "NODE_COORD_SECTION\n");
	fprintf(stdout, "\nHeader was written. . .\n");

	int i, j, x, y;
	int flag[MAX - MIN][MAX - MIN];
	for (i = 0; i < MAX - MIN; i++)
		for (j = 0; j < MAX - MIN; j++)
			flag[i][j] = 0;

	for (i = 1; i <= size; i++) {

		//	Generate the next random node, checking for doubles.
		x = nextRandom(MIN, MAX);
		y = nextRandom(MIN, MAX);
		while(flag[x - MIN][y - MIN] == 1) {
			x = nextRandom(MIN, MAX);
			y = nextRandom(MIN, MAX);
		}

		fprintf(file, "%d %d %d\n", i, x, y);
		flag[x - MIN][y - MIN] = 1;
	}

	//	Print EOF and close file.
	fprintf(file, "EOF\n");
	fclose(file);

	fprintf(stdout, "\nFile was written, terminating. . .\n");
	return 0;
}
